package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.CdbInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IFirmware;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.HintDialog;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/7/11 12:48
 * 邮箱：zhanghuaiha@gmail.com
 */

public class FirmwarePresenter extends BasePresenter<IFirmware> {

    private String versionName;
    private String eid;
    private String udid;
    private int firmware_version;
    private int count = 1;
    private String alias;
    private ImageView one;
    private ImageView two;
    private ImageView three;
    private ImageView four;
    private ImageView five;
    private ImageView six;
    private ImageView seven;
    private int type = 1;
    private static final int UPDATE = 101;
    private static final int UPDATE_CDB = 102;
    private static final int QUERY_CDB = 103;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE) {
                update_cdb();
            }else if (msg.what == UPDATE_CDB) {
                Glide.with(mContext).load(R.drawable.wancheng).into(seven);
                progressDialog.dismiss();
                ToastUtil.showToast(mContext.getString(R.string.success_update));
            }else if (msg.what == QUERY_CDB) {
                String string =  (String)msg.obj;
                getMessage(string);
            }
        }
    };
    private Integer zuixin;
    private int dangqian;
    private Dialog progressDialog;


    public FirmwarePresenter(BaseActivity context) {
        super(context);
    }

    public void loadDate(String alias){
        versionName = ObtainVersion.getVersionName(mContext);
        eid = App.SP.getString("id", "");
        udid = App.SP.getString("udid", "");
        this.alias = alias;
        one = getView().getOne();
        two = getView().getTwo();
        three = getView().getThree();
        four = getView().getFour();
        five = getView().getFive();
        six = getView().getSix();
        seven = getView().getSeven();
    }

    public void getType(int cunt){
        if (cunt == 2) {
            type = 2;
        }else {
            type = 3;
        }
        count = 1;


    }

    //查找设备
    public void getCdb_info() {
        if (count != 1) {
            //第四个图标转动
            Glide.with(mContext).load(R.drawable.zhuan_ing).into(four);
        }else {
            if (type == 2) {
                dialogs("正在检测最新版本..");
            }else {
                dialogs("正在更新..");
            }
            //第一个图标转动
            Glide.with(mContext).load(R.drawable.zhuan_ing).into(one);
        }
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getCdb_info("2", time, versionName, NetWorkCodeInfo.GETCDB_INFO, udid, eid, alias);
        RetrofitFactory.getmInstanse().mApi.getCdb_info("2", time, versionName, NetWorkCodeInfo.GETCDB_INFO, udid, eid, alias, encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<CdbInfo>>() {
                    @Override
                    public void success(BaseResponseEntity<CdbInfo> cdbInfoBaseResponseEntity) {
                        if (count != 1) {
                            getTwoDate(cdbInfoBaseResponseEntity);
                        }else {
                            getOneDate(cdbInfoBaseResponseEntity);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        if (count != 1) {
                            //第四个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(four);
                        }else {
                            //第一个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(one);
                        }
                        progressDialog.dismiss();
                       // ToastUtil.showToast(mContext.getString(R.string.e_firmware));
                    }
                });
    }


    public void getOneDate(BaseResponseEntity<CdbInfo> cdbInfoBaseResponseEntity){
        if (cdbInfoBaseResponseEntity.code == 200) {
            CdbInfo data = cdbInfoBaseResponseEntity.data;
            if (data != null) {
                if (data.getCharging().getFirmware_version() != null) {
                    int firmware = App.SP.getInt("firmware", 0);
                    if (firmware != 0) {
                        if (data.getCharging().getFirmware_version() != null && Integer.parseInt((String)data.getCharging().getFirmware_version()) < firmware) {
                            //第一个图标完成
                            Glide.with(mContext).load(R.drawable.wancheng).into(one);
                            //第二个图标转动
                            Glide.with(mContext).load(R.drawable.zhuan_ing).into(two);
                            getFirmware();
                        } else {
                            zuixin = firmware;
                            dangqian = Integer.parseInt((String)data.getCharging().getFirmware_version());
                            //第一个图标完成
                            Glide.with(mContext).load(R.drawable.wancheng).into(one);
                            progressDialog.dismiss();
                            Dialog();
                           // ToastUtil.showToast(mContext.getString(R.string.success_firmware));
                        }
                    }else {
                        //第一个图标完成
                        Glide.with(mContext).load(R.drawable.wancheng).into(one);
                        //第二个图标转动
                        Glide.with(mContext).load(R.drawable.zhuan_ing).into(two);
                        getFirmware();
                    }
                }else {
                    //第一个图标完成
                    Glide.with(mContext).load(R.drawable.wancheng).into(one);
                    //第二个图标转动
                    Glide.with(mContext).load(R.drawable.zhuan_ing).into(two);
                    getFirmware();

                }
            }else {
                //第一个图标失败
                Glide.with(mContext).load(R.drawable.shibai).into(one);
                progressDialog.dismiss();
                ToastUtil.showToast(mContext.getString(R.string.error_date));
            }

        } else {
            //第一个图标失败
            Glide.with(mContext).load(R.drawable.shibai).into(one);
            progressDialog.dismiss();
            ToastUtil.showToast(cdbInfoBaseResponseEntity.message);
        }
    }


    public void getTwoDate(BaseResponseEntity<CdbInfo> cdbInfoBaseResponseEntity){
        if (cdbInfoBaseResponseEntity.code == 200) {
            CdbInfo data = cdbInfoBaseResponseEntity.data;
            if (data != null) {
                if (type == 2) {
                    if (cdbInfoBaseResponseEntity.data.getCharging().getFirmware_version() == null) {
                        if (cdbInfoBaseResponseEntity.data.getCharging().getOn_line().equals("0")){
                            ToastUtil.showToast("当前设备不在线");
                            Glide.with(mContext).load(R.drawable.shibai).into(four);
                        }else {
                            Glide.with(mContext).load(R.drawable.shibai).into(four);
                            Dialog();
                        }
                        progressDialog.dismiss();
                    }else {
                        dangqian = Integer.parseInt((String) cdbInfoBaseResponseEntity.data.getCharging().getFirmware_version());
                        //第四个图标完成
                        Glide.with(mContext).load(R.drawable.wancheng).into(four);
                        progressDialog.dismiss();
                        getFir();
                    }
                }else {
                    firmware_version = Integer.parseInt((String)data.getCharging().getFirmware_version());
                    int firmware = App.SP.getInt("firmware", 0);
                    if (firmware != 0) {
                        if (Integer.parseInt((String)data.getCharging().getFirmware_version()) < firmware) {
                            //第四个图标完成
                            Glide.with(mContext).load(R.drawable.wancheng).into(four);
                            //第五个图标转动
                            Glide.with(mContext).load(R.drawable.zhuan_ing).into(five);
                            getFirmware();
                        } else {

                            //第四个图标完成
                            Glide.with(mContext).load(R.drawable.wancheng).into(four);
                            progressDialog.dismiss();
                            ToastUtil.showToast(mContext.getString(R.string.success_firmware));
                        }
                    }else {
                        //第四个图标完成
                        Glide.with(mContext).load(R.drawable.wancheng).into(four);
                        //第五个图标转动
                        Glide.with(mContext).load(R.drawable.zhuan_ing).into(five);
                        getFirmware();
                    }
                }
            }else {
                //第四个图标失败
                Glide.with(mContext).load(R.drawable.shibai).into(four);
                progressDialog.dismiss();
                ToastUtil.showToast(mContext.getString(R.string.error_date));
            }

        } else {
            //第四个图标失败
            Glide.with(mContext).load(R.drawable.shibai).into(four);
            progressDialog.dismiss();
            ToastUtil.showToast(cdbInfoBaseResponseEntity.message);
        }
    }



    //获取最新固件版本
    public void getFirmware(){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getVersion("2", time, versionName, NetWorkCodeInfo.FIRMWARE, udid);
        RetrofitFactory.getmInstanse().mApi.getFirmware("2",time,versionName,NetWorkCodeInfo.FIRMWARE,udid,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<Integer>>() {
                    @Override
                    public void success(BaseResponseEntity<Integer> integerBaseResponseEntity) {
                        zuixin = integerBaseResponseEntity.data;
                        if (count != 1) {
                            getTwoFir(integerBaseResponseEntity);
                        }else {
                            getOneFir(integerBaseResponseEntity);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (count != 1) {
                            //第五个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(five);
                        }else {
                            //第二个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(two);
                        }
                        progressDialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_firmware));
                    }
                });
    }


    public void getOneFir(BaseResponseEntity<Integer> integerBaseResponseEntity){
        if (integerBaseResponseEntity.code == 200) {
            //如果当前设备的固件版本小于服务器的固件版本那么就升级固件
            if (firmware_version < integerBaseResponseEntity.data) {
                //第二个图标完成
                Glide.with(mContext).load(R.drawable.wancheng).into(two);
                //第三个图标转动
                Glide.with(mContext).load(R.drawable.zhuan_ing).into(three);
                getQuery_sv();
            }else {
                //第二个图标完成
                Glide.with(mContext).load(R.drawable.wancheng).into(two);
                progressDialog.dismiss();
                ToastUtil.showToast(mContext.getString(R.string.success_firmware));
            }
            App.EDIT.putInt("firmware",integerBaseResponseEntity.data);
            App.EDIT.commit();
        }else {
            //第二个图标失败
            Glide.with(mContext).load(R.drawable.shibai).into(two);
            progressDialog.dismiss();
            ToastUtil.showToast(integerBaseResponseEntity.message);
        }
    }

    public void getTwoFir(BaseResponseEntity<Integer> integerBaseResponseEntity){
        if (integerBaseResponseEntity.code == 200) {
            //如果当前设备的固件版本小于服务器的固件版本那么就升级固件
            if (firmware_version < integerBaseResponseEntity.data) {
                //第五个图标完成
                Glide.with(mContext).load(R.drawable.wancheng).into(five);
                //第六个图标转动
                Glide.with(mContext).load(R.drawable.zhuan_ing).into(six);
                getQuery_sv();
            }else {
                //第五个图标完成
                Glide.with(mContext).load(R.drawable.wancheng).into(five);
                progressDialog.dismiss();
                ToastUtil.showToast(mContext.getString(R.string.success_firmware));
            }
            App.EDIT.putInt("firmware",integerBaseResponseEntity.data);
            App.EDIT.commit();
        }else {
            //第五个图标失败
            Glide.with(mContext).load(R.drawable.shibai).into(five);
            progressDialog.dismiss();
            ToastUtil.showToast(integerBaseResponseEntity.message);
        }
    }



    //查询指令链路情况
    public void getQuery_sv(){
        String tiemMessage = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getQuery("2", tiemMessage, versionName, NetWorkCodeInfo.QUERY_SV, udid, eid,alias);

        RetrofitFactory.getmInstanse().mApi.getQuery_sv("2", tiemMessage, versionName, NetWorkCodeInfo.QUERY_SV, udid, eid, alias,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (count != 1) {
                            if (stringBaseResponseEntity.code == 200) {
                                handler.sendMessageDelayed(handler.obtainMessage(QUERY_CDB,stringBaseResponseEntity.data), 2000);
                            }else {
                                //第六个图标失败
                                Glide.with(mContext).load(R.drawable.shibai).into(six);
                                progressDialog.dismiss();
                               // ToastUtil.showToast(stringBaseResponseEntity.message);
                            }
                        }else {
                            if (stringBaseResponseEntity.code == 200) {
                                handler.sendMessageDelayed(handler.obtainMessage(QUERY_CDB,stringBaseResponseEntity.data), 2000);
                            }else {
                                //第三个图标失败
                              // progressDialog.dismiss();
                                handler.sendMessageDelayed(handler.obtainMessage(QUERY_CDB,stringBaseResponseEntity.data), 2000);
                                Glide.with(mContext).load(R.drawable.wancheng).into(three);

                               // ToastUtil.showToast(stringBaseResponseEntity.message);
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (count != 1) {
                            //第六个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(six);
                        }else {
                            //第三个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(three);
                        }
                        progressDialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_hint));
                    }
                });
    }

    //查询指令链路情况
    public void getMessage(String message){
        String tiemMessage = System.currentTimeMillis() + "";
        String encryMessage = ObtainEncry.getMessage("2", tiemMessage, versionName, NetWorkCodeInfo.MESSAGE_STATUS, udid, message);

        RetrofitFactory.getmInstanse().mApi.getMessage("2", tiemMessage, versionName, NetWorkCodeInfo.MESSAGE_STATUS, udid, message, encryMessage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (stringBaseResponseEntity.code == 200) {
                            if (count == 1) {
                                //第三个图标完成
                                Glide.with(mContext).load(R.drawable.wancheng).into(three);
                                count++;
                                getCdb_info();
                            }else {
                                //第六个图标完成
                                Glide.with(mContext).load(R.drawable.wancheng).into(six);
                                //更新设备
                                //第七个图标转动
                                Glide.with(mContext).load(R.drawable.zhuan_ing).into(seven);
                                handler.sendMessageDelayed(handler.obtainMessage(UPDATE), 2000);
                            }
                            ToastUtil.showToast(mContext.getString(R.string.success));
                        }else {
                            if (count == 1) {
                                //第三个图标完成
                                Glide.with(mContext).load(R.drawable.wancheng).into(three);
                                count++;
                                getCdb_info();
                            }else {
                                //第六个图标完成
                                Glide.with(mContext).load(R.drawable.wancheng).into(six);
                                //更新设备
                                //第七个图标转动
                                Glide.with(mContext).load(R.drawable.zhuan_ing).into(seven);
                                handler.sendMessageDelayed(handler.obtainMessage(UPDATE), 2000);
                            }
                           // progressDialog.dismiss();
                            //ToastUtil.showToast(stringBaseResponseEntity.message);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (count == 1) {
                            //第三个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(three);
                        }else {
                            //第六个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(six);
                        }
                        progressDialog.dismiss();
                       ToastUtil.showToast(mContext.getString(R.string.error_hint));
                    }
                });
    }


    //更新设备
    public void update_cdb(){
        String tiemMessage = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getQuery("2", tiemMessage, versionName, NetWorkCodeInfo.UPDATE_SV, udid, eid,alias);
        RetrofitFactory.getmInstanse().mApi.getUpdate_sv("2", tiemMessage, versionName, NetWorkCodeInfo.UPDATE_SV, udid, eid, alias,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (stringBaseResponseEntity.code == 200) {
                            //第七个图标完成
                            handler.sendMessageDelayed(handler.obtainMessage(UPDATE_CDB), 30*1000);
                        }else {
                            //第七个图标失败
                            Glide.with(mContext).load(R.drawable.shibai).into(seven);
                            progressDialog.dismiss();
                            ToastUtil.showToast(stringBaseResponseEntity.message);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        //第七个图标失败
                        Glide.with(mContext).load(R.drawable.shibai).into(seven);
                        progressDialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_update));
                    }
                });
    }




    //查找设备
    public void getCdb() {
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getCdb_info("2", time, versionName, NetWorkCodeInfo.GETCDB_INFO, udid, eid, alias);
        RetrofitFactory.getmInstanse().mApi.getCdb_info("2", time, versionName, NetWorkCodeInfo.GETCDB_INFO, udid, eid, alias, encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<CdbInfo>>() {
                    @Override
                    public void success(BaseResponseEntity<CdbInfo> cdbInfoBaseResponseEntity) {
                        if (cdbInfoBaseResponseEntity.code == 200) {
                            dangqian = Integer.parseInt((String) cdbInfoBaseResponseEntity.data.getCharging().getFirmware_version());
                            getFir();
                        }else {
                            ToastUtil.showToast(cdbInfoBaseResponseEntity.message);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        ToastUtil.showToast(mContext.getString(R.string.e_firmware));
                    }
                });
    }


    //获取最新固件版本
    public void getFir(){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getVersion("2", time, versionName, NetWorkCodeInfo.FIRMWARE, udid);
        RetrofitFactory.getmInstanse().mApi.getFirmware("2",time,versionName,NetWorkCodeInfo.FIRMWARE,udid,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<Integer>>() {
                    @Override
                    public void success(BaseResponseEntity<Integer> integerBaseResponseEntity) {
                        if (integerBaseResponseEntity.code == 200) {
                            zuixin = integerBaseResponseEntity.data;
                            Dialog();
                        }else {
                            progressDialog.dismiss();
                            ToastUtil.showToast(integerBaseResponseEntity.message);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        progressDialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_firmware));
                    }
                });
    }

    public void Dialog() {
        HintDialog selfDialog = new HintDialog(mContext);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("当前版本："+dangqian+"\r\n最高版本："+zuixin);
        selfDialog.show();
        progressDialog.dismiss();

    }

    public void dialogs(String message){
        progressDialog = new Dialog(mContext,R.style.progress_dialog);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setContentView(R.layout.dialog);
        progressDialog.setCancelable(true);
        progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText(message);
        progressDialog.show();
    }
}
